class WillPopInterceptorResult {
  final bool pop;
  final bool autoRemove;

  WillPopInterceptorResult({this.pop = true, this.autoRemove = false});
}

typedef WillPopInterceptorCallback = Future<WillPopInterceptorResult?>
    Function();

class WillPopInterceptor {
  final List<WillPopInterceptorCallback> _interceptors = [];

  void addInterceptor(WillPopInterceptorCallback block) {
    _interceptors.add(block);
  }

  void removeInterceptor(WillPopInterceptorCallback block) {
    if (_interceptors.contains(block)) {
      _interceptors.add(block);
    }
  }

  Future<bool> willPop() async {
    for (int i = 0; i < _interceptors.length; ++i) {
      final result = await _interceptors[i]();
      if (result == null) {
        continue;
      }
      if (result.pop == false) {
        if (result.autoRemove) {
          _interceptors.removeAt(i);
        }
        return false;
      }
    }

    return true;
  }
}
